/**
 * Copyright © 2014 TingerSure. All rights reserved.
 */
package org.sure.scomet.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sure.scomet.link.Connection;
import org.sure.scomet.link.ConnectionCenter;
import org.sure.scomet.util.log.LogManager;
import org.sure.scomet.util.log.LogType;

/**
 * The action which is held by Server to send message to the client.
 * 
 * @author TingerSure
 * 
 */
public class ConnectionAction {
	/**
	 * The connection action.<br>
	 * It will be called when the connection request come.
	 * 
	 * @param req
	 *            the request
	 * @param res
	 *            the response
	 */
	public void Action(HttpServletRequest req, HttpServletResponse res) {
		try {
			int id = Integer.parseInt(req.getParameter("id"));
			if (!ConnectionCenter.getCallBack().role(id, req.getSession())) {
				LogManager.log(
						"wrong request role in connection -> "
								+ req.getRemoteUser() + "@"
								+ req.getRemoteHost() + ":"
								+ req.getRemotePort(), LogType.warn);
				PrintWriter write = null;
				write = res.getWriter();
				write.write("c:");
				return;
			}
			Connection conn = ConnectionCenter.getConnection(id);
			conn.setSend(this);
			synchronized (this) {
				this.wait(ConnectionCenter.getMaxWaitTime());
			}
			PrintWriter write = null;
			write = res.getWriter();
			write.write(message);
		} catch (IOException e) {
			LogManager.logException("message return error ", e, LogType.error);
		} catch (InterruptedException e) {
			LogManager.logException("Connection error!", e, LogType.error);
		}

	}

	/**
	 * message type
	 */
	private String message = "m:";

	/**
	 * set message what will be sent to the client.
	 * 
	 * @param message
	 */
	public void setMessage(String message) {
		if (message == null) {
			this.message = "c:";
		}
		this.message = "m:" + message;

	}

}
